--
-- Author:      name
-- DateTime:    2018-04-26 17:10:35
-- Description: 与机器人客户端通信
local skynet = require "skynet"
local log = require "Log"
local config = require "configquery"
local pbc = require "pbc_helper"
--local pbc = require "pbc_helper"
require "skynet.manager"
local Objects = require "Objects"
local msgpack = require "msgpack_helper"
local Message = require "robot.Message"
local Command = require "robot.Command"


g_objects = Objects.new()
local CMD = {}
local SOCKET = {}
local command

function SOCKET.open(gate, fd, addr)
	log.debug("new web fd:" ..fd .." from :".. addr)
	local fd        = fd
	local gate      = gate
	skynet.call(gate, "lua", "forward", fd)
	command:addfd(fd)
end

function SOCKET.close(gate, fd)
	command:remove(fd)
end

function SOCKET.error(gate, fd, msg)

end

function SOCKET.warning(gate, fd, size)
	-- size K bytes havn't send out in fd
end

function SOCKET.data(gate, fd, msg)
	print("__________1")
end

function CMD.socket( source, cmd, ... )
	local f = SOCKET[cmd]
	if f then
		f(source, ...)
	end
end


local function init()

	local message = Message.new()
	g_objects:add(message)
	command = Command.new(message)
	g_objects:add(command)
	g_objects:hotfix("robot")
	--proto
	local proto_file = skynet.getenv("proto_config")
	local pbc_env = pbc.init(proto_file, {'base','gate','game','robot'})
	msgpack.load(pbc_env)
	--socket
	local svr_config = config.setting_cfg["globalsvr"]
	local conf = {
			port = svr_config.robot_port,
			maxclient = svr_config.robot_maxclient,
		}
	local gate = skynet.newservice("gate")
	skynet.call(gate, "lua", "open", conf)
	print("_______________robot_service____",svr_config.robot_port)
	skynet.register_protocol{
		name = "client",
		id = skynet.PTYPE_CLIENT,
		unpack = msgpack.unpack_message,
							
		dispatch = function (fd, address, sid, pack_name, pack_body)
			if not pack_name or not pack_body then
				print("#####____not pock_id or not pack_body______",pack_name,pack_body)
				return 
			end
			for msg,args in pairs(pack_body) do
				local ok, result  = pcall(message:dispatch(), fd, msg, args)
				if not ok then
					log.error(result)
				end
			end
		end
	}

	skynet.dispatch("lua", message:dispatchSelfHandle())
end


---------------------------------------------------------
-- skynet
---------------------------------------------------------

skynet.start(function()
	init()
	-- skynet.dispatch("lua", dispatch_command(CMD))
	skynet.register "robot_service"
end)